from tokenizer import Tokenizer
from parser import Parser
from formatter import Formatter
from checker import Checker
import consts
import exception

TypeJsonParseError = exception.TypeJsonParseError


class Processor:
    def __init__(self):
        self.holder = []
        self.formatter = Formatter()

    def compile(self, src_list, hold=True):
        parse_results = []
        for src in src_list:
            parse_result = Parser(Tokenizer(src)).parse()
            parse_results.append(parse_result)
        format_result = self.formatter.format(parse_results, self.holder)
        for ast in format_result:
            defs = ast[consts.AST_DEF]
            for a_def in defs:
                Checker.check_def_type(a_def)
                Checker.check_def_members(a_def)
            obj = ast[consts.AST_VALUE]
            if obj:
                t = obj.type_ref_symbol
                Checker.check_value(t, t is not None, obj.value)
        if hold:
            self.holder += format_result
        return format_result

    def loads(self, s):
        res = self.compile([s], False)[0]
        return res[consts.AST_VALUE].value.res_value


common_processor = Processor()


def loads(s):
    return common_processor.loads(s)
